package cn.edu.jnu.supershopper;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShareFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShareFragment extends Fragment {
    private List<String> list_book = new ArrayList<>();
    private ArrayList<Book> BookList = new ArrayList<>();
    private ListView mListView;
    public ShareFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @return A new instance of fragment ShareFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShareFragment newInstance() {
        ShareFragment fragment = new ShareFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_share, container, false);
        BookDataSaver bookDataSaver =new BookDataSaver();
        BookList= bookDataSaver.Load(getContext());
        for(Book book:BookList){
            list_book.add(book.getName());
        }
        String[] mStr = list_book.toArray(new String[list_book.size()]);

        mListView = (ListView) root.findViewById(R.id.listView);
        mListView.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, mStr));

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String isbn = BookList.get(i).getIsbn();
                if(!isbn.equals("暂无信息")){
                    Intent intent = new Intent(getContext(), Share_Code.class);
                    intent.putExtra("ISBN", isbn);
                    startActivity(intent);
                }
                else
                    Toast.makeText(getContext(), "请检查ISBN码是否正确", Toast.LENGTH_SHORT).show();

            }
        });
        return root;
    }
}